#!/usr/bin/env bash
GUEST_TIMEOUT=25
BUILD_DIR=$1
SCHED=$2
KERNEL=$3
DIFF_DIR=$4

if [ "${KERNEL}" == "vmlinuz" ]; then
  unset KERNEL
fi

cd $build_dir

if [ -n "${KERNEL}" ] && [ ! -x `which vng` ]; then
  echo "vng not found, please install virtme-ng to enable testing"
  exit 1
fi

if [ -n "${SCHED}" ]; then
  BPF_PATH=$(find ${BUILD_DIR} -type f -name bpf.bpf.o | grep ${SCHED})
  echo "Running veristat on ${BPF_PATH}"
  if [ -n "${KERNEL}" ]; then
    timeout --preserve-status ${GUEST_TIMEOUT} \
      vng -m 2G -v --rwdir "${DIFF_DIR}" --user root -r ${KERNEL} -- \
        veristat ${BPF_PATH} -o csv > "${DIFF_DIR}/${SCHED}_new.csv" \
	  || echo "failed to verify ${SCHED}: ${BPF_PATH}"
    if [ -n "${DIFF_DIR}" ]; then
      timeout --preserve-status ${GUEST_TIMEOUT} \
        vng -m 2G -v --rwdir "${DIFF_DIR}" --user root -r ${KERNEL} -- \
          veristat -C "${DIFF_DIR}/${SCHED}_new.csv" "${DIFF_DIR}/${SCHED}.csv" \
	    -e file,prog,verdict,insns \
	    || echo "failed to compare ${SCHED}: ${BPF_PATH}"
    fi
    exit $?
  else
    echo "saving veristat diff for ${SCHED}.csv"
    sudo veristat ${BPF_PATH} -o csv > "${SCHED}.csv"
    if [ -n "${DIFF_DIR}" ]; then
      sudo veristat -C "${SCHED}.csv" "${DIFF_DIR}/${SCHED}.csv" \
        -e file,prog,verdict,insns
    fi
    exit $?
  fi
fi

for BPF_PATH in $(find ${BUILD_DIR} -type f -name bpf.bpf.o); do
  SCHED=$(echo "${BPF_PATH}" | sed 's/.*\/rust\///g' | sed 's/\/.*//g')
  if [ -n "${KERNEL}" ]; then
    timeout --preserve-status ${GUEST_TIMEOUT} \
      vng -m 2G -v --rwdir "${DIFF_DIR}" --user root -r ${KERNEL} -- \
        veristat ${BPF_PATH} -o csv > "${DIFF_DIR}/${SCHED}_new.csv" \
          || echo "failed to verify ${SCHED}: ${BPF_PATH}"
    if [ -n "${DIFF_DIR}" ]; then
      timeout --preserve-status ${GUEST_TIMEOUT} \
        vng -m 2G -v --rwdir "${DIFF_DIR}" --user root -r ${KERNEL} -- \
          veristat -C "${SCHED}_new.csv" "${DIFF_DIR}/${SCHED}.csv" \
	    -e file,prog,verdict,insns \
            || echo "failed to compare ${SCHED}: ${BPF_PATH}"
    fi
  else
    echo "saving veristat diff for ${SCHED}.csv"
    sudo veristat ${BPF_PATH} -o csv > "${SCHED}.csv"
    if [ -n "${DIFF_DIR}" ]; then
      sudo veristat -C "${SCHED}.csv" "${DIFF_DIR}/${SCHED}.csv" \
        -e file,prog,verdict,insns
    fi
  fi
done
